/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author workshop
 */
public class CleanThread extends Thread{
    int maxNumThreads;
    ClientThread[] threads;
    GUIControl guiControl;
    String[] threadFields =  {"thread ID","Username","Running Time"};
    
    public CleanThread(int maxNumThreads,ClientThread[] threads,GUIControl guiControl){
        this.maxNumThreads = maxNumThreads;
        this.threads = threads;
        this.guiControl = guiControl;
    }
    
    @Override
     public void run(){
        while(true){
            for(int i = 0; i < this.maxNumThreads; i++){
                checkThreadAndKill(i);
            }
            ArrayList<Integer> pids = new ArrayList<>();
            for(int i = 0; i < this.maxNumThreads; i++){
                if(threads[i] != null){
                    pids.add(i);
                }
            }
            String[][] data = new String[pids.size()][3];
            for(int i = 0; i < pids.size(); i++){
                data[i][0] = "" + pids.get(i);
                data[i][1] = threads[pids.get(i)].loginMsn.username;
                double timeElapsed = (double)(System.currentTimeMillis() - threads[pids.get(i)].startTime)/1000;
                if(timeElapsed > 60){
                    data[i][2] = "" + (int)(timeElapsed / 60) +" mins " + ((int)timeElapsed % 60) + " secs";
                }
                else{
                    data[i][2] = "" + timeElapsed + " secs";
                }
            }
            this.guiControl.setTable(threadFields, data);
            
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(CleanThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public synchronized void checkThreadAndKill(int threadIdx){
        if (threads[threadIdx] != null) {
            if (threads[threadIdx].isThreadFinish()) {
                try {
                    threads[threadIdx].closeConnection();
                } catch (IOException ex) {
                    Logger.getLogger(CleanThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                threads[threadIdx] = null;
            }
        }
    }
}
